package com.zmn.oms.services.impl.order;

import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.model.dto.order.OrderDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.discount.OrderDiscount;
import com.zmn.oms.model.entity.order.Order;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.persistence.interfaces.order.OrderDao;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.discount.OrderDiscountService;
import com.zmn.oms.services.interfaces.order.OrderService;
import com.zmn.oms.services.interfaces.product.OrderProductService;
import com.zmn.saas.common.utils.EmojiUtil;
import io.shardingsphere.api.HintManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 类描述：订单
 *
 * @author liuying
 * @date 2018/11/06 11:41
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderDao orderDao;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private OrderProductService orderProductService;

    @Autowired
    private OrderDiscountService orderDiscountService;

    @Override
    public Order findOrderByKey(Long orderId) {
        return orderDao.findByKey(orderId);
    }

    @Override
    public Order findOrderByKeySrcMaster(Long orderId) {
        try (HintManager hintManager = HintManager.getInstance()) {
            hintManager.setMasterRouteOnly();
            return findOrderByKey(orderId);
        }
    }

    @Override
    public void updateConfirmStatus(Order order) {
        orderDao.updateConfirmStatus(order);
    }

    @Override
    public void updateTakeOrVisitStatus(Order order, Map<String, Boolean> fields) {
        orderDao.updateTakeOrVisitStatus(order, fields);
    }

    @Override
    public void updateOrderByKey(Order order) {
        if (order.getUpdateTime() == null) {
            order.setUpdateTime(DateUtil.getNow());
        }
        orderDao.updateByKey(order);
    }

    @Override
    public void updateOrder(OrderDTO orderDTO) {
        Order order = orderDTO.getOrder();
        OrderDetail orderDetail = orderDTO.getOrderDetail();
        List<OrderProduct> orderProducts = orderDTO.getOrderProductList();
        List<OrderDiscount> orderDiscountList = orderDTO.getOrderDiscountList();

        Date updateTime = DateUtil.getNow();
        order.setUpdateTime(updateTime);
        orderDao.updateByKey(order);
        Long orderId = order.getOrderId();

        // 保存详情
        orderDetail.setDetailId(orderId);
        orderDetail.setUpdater(order.getUpdater());
        orderDetail.setUpdateTime(updateTime);

        orderDetailService.updateOrderDetailByKey(orderDetail);

        // 删除并新增产品
        if (CollectionUtils.isNotEmpty(orderProducts)) {
            // 查询产品是否有变化
            orderProductService.deleteOrderProductByOrderId(order.getOrderId());
            // 保存产品
            orderProducts.forEach((item) -> {
                item.setOrderId(orderId);
                item.setCreater(order.getUpdater());
                item.setCreateTime(updateTime);
            });
            orderProductService.insertOrderProductList(orderProducts);
        }

        // 删除并新增优惠
//        if (CollectionUtils.isNotEmpty(orderDiscountList)) {
//            orderDiscountService.deleteByOrderId(order.getOrderId());
//            // 保存优惠
//            orderDiscountList.forEach((item) -> {
//                item.setOrderId(orderId);
//                item.setCreater(order.getCreater());
//                item.setCreateTime(updateTime);
//            });
//            orderDiscountService.insertOrderDiscountList(orderDiscountList);
//        }
    }

    @Override
    public void updateOrderAddress(OrderDTO orderDTO) {
        Order order = orderDTO.getOrder();
        OrderDetail orderDetail = orderDTO.getOrderDetail();

        if (BooleanUtils.isNotTrue(orderDTO.getUpdateAddress())) {
            orderDao.updateAddressByKey(order);
            Long orderId = order.getOrderId();

            // 保存详情
            orderDetail.setDetailId(orderId);
        }

        orderDetail.setUpdater(orderDTO.getOperator());
        orderDetailService.updateOrderDetailAddressByKey(orderDetail);
    }

    @Override
    public void updateSyncOrder(Order order) {
        orderDao.updateSyncOrder(order);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long insertOrderAndProduct(OrderDTO orderDTO) {
        Order order = orderDTO.getOrder();

        String creater = order.getCreater();
        if (StringUtil.isNotBlank(creater)) {// 表情符号转换为字符
            creater = EmojiUtil.filterEmoji(creater);
        }
        OrderDetail orderDetail = orderDTO.getOrderDetail();
        List<OrderProduct> orderProducts = orderDTO.getOrderProductList();
        Date createTime = Optional.ofNullable(orderDetail.getCreateTime()).orElse(DateUtil.getNow());
        order.setCreateTime(createTime);
        order.setUpdateTime(createTime);
        order.setCreater(creater);
        if (order.getStatus() == null) {
            order.setStatus(OrderStatusConsts.ORDER_STATUS_INPUT);
        }

        orderDao.insertOrder(order);

        // 订单ID
        Long orderId = order.getOrderId();

        // 保存详情
        orderDetail.setDetailId(orderId);
        orderDetail.setCreater(creater);
        orderDetail.setCreateTime(createTime);

        orderDetailService.insertOrderDetail(orderDetail);

        // 保存产品
        for (OrderProduct orderProduct : orderProducts) {
            orderProduct.setOrderId(orderId);
            orderProduct.setCreater(creater);
            orderProduct.setCreateTime(createTime);
        }
        orderProductService.insertOrderProductList(orderProducts);
        return orderId;
    }

}
